package com.gomro.galaxy.foundation.bi.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gomro.galaxy.core.commons.elastic.ElasticSearchRest;
import com.gomro.galaxy.core.commons.response.RestResponse;
import com.gomro.galaxy.foundation.bi.domain.Constants;
import com.gomro.galaxy.foundation.bi.domain.model.analysis.SalesDataComparisonStatisticsVolume;
import com.gomro.galaxy.foundation.bi.domain.model.analysis.SalesDataComparisonStatisticsVolumeView;
import com.gomro.galaxy.foundation.bi.query.SalesDataComparisonStaticsQuery;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.BucketOrder;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.*;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
    //销售数据比service
@Service
public class SalesDataComparisonStaticsService {
    private final ElasticSearchRest rest;
    private final RestHighLevelClient client;
    private final ObjectMapper mapper;
    private static final String INDEX = Constants.BiDataMartIndexPrefix + SalesDataComparisonStatisticsVolume.TableName;
             //销售数据比service
    public SalesDataComparisonStaticsService(RestHighLevelClient client, ObjectMapper mapper) {
        this.client = client;
        this.mapper = mapper;
        this.rest = new ElasticSearchRest(client, mapper);
    }

    public RestResponse<List<SalesDataComparisonStatisticsVolumeView>> page(SalesDataComparisonStaticsQuery query) {
        //构建查询                      获取查询生成器
        QueryBuilder queryBuilder = this.getQueryBuilder(query);



        TermsAggregationBuilder orgTerm = AggregationBuilders.terms("terms").field("businessId").order(BucketOrder.key(true)).size(query.getPage() * query.getLimit());
        CardinalityAggregationBuilder count = AggregationBuilders.cardinality("count").field("businessId");
        //询价商品数   聚合生成器
        AggregationBuilder inquiryGoodsNumber = AggregationBuilders.sum("inquiryGoodsNumber").field("inquiryGoodsNumber");
        AggregationBuilder businessName = AggregationBuilders.topHits("businessName").docValueField("businessName.keyword").size(1);
        AggregationBuilder organizationId = AggregationBuilders.cardinality("organizationId").field("organizationId");
        //报价商品数量-原有供应商
        AggregationBuilder originalQuotationNumber = AggregationBuilders.sum("originalQuotationNumber").field("originalQuotationNumber");
        //报价商品数量-平台供应商
        AggregationBuilder platformQuotationNumber = AggregationBuilders.sum("platformQuotationNumber").field("platformQuotationNumber");
        //报价商品数量-未报价
        AggregationBuilder notQuotedGoodsNumber = AggregationBuilders.sum("notQuotedGoodsNumber").field("notQuotedGoodsNumber");
        //定标商品数量-原有供应商
        AggregationBuilder originalTargetGoodsNumber = AggregationBuilders.sum("originalTargetGoodsNumber").field("originalTargetGoodsNumber");
        //定标商品数量-平台供应商
        AggregationBuilder platfromTargetGoodsNumber = AggregationBuilders.sum("platfromTargetGoodsNumber").field("platfromTargetGoodsNumber");
        //订单商品数-原有供应商
        AggregationBuilder originalOrderGoodsNumber = AggregationBuilders.sum("originalOrderGoodsNumber").field("originalOrderGoodsNumber");
        //订单商品数-平台供应商
        AggregationBuilder platfromOrderGoodsNumber = AggregationBuilders.sum("platfromOrderGoodsNumber").field("platfromOrderGoodsNumber");
        //订单数量
        AggregationBuilder orderNumber = AggregationBuilders.sum("orderNumber").field("orderNumber");
        //订单金额-原有供应商
        AggregationBuilder originalOrderAmount = AggregationBuilders.sum("originalOrderAmount").field("originalOrderAmount");
        //订单金额-平台供应商
        AggregationBuilder platfromOrderAmount = AggregationBuilders.sum("platfromOrderAmount").field("platfromOrderAmount");
        //退货金额-原有供应商
        AggregationBuilder originalReturnAmount = AggregationBuilders.sum("originalReturnAmount").field("originalReturnAmount");
        //退货金额-平台供应商
        AggregationBuilder platfromReturnAmount = AggregationBuilders.sum("platfromReturnAmount").field("platfromReturnAmount");

        orgTerm.subAggregation(inquiryGoodsNumber);
        orgTerm.subAggregation(businessName);
        orgTerm.subAggregation(organizationId);
        orgTerm.subAggregation(originalQuotationNumber);
        orgTerm.subAggregation(platformQuotationNumber);
        orgTerm.subAggregation(notQuotedGoodsNumber);
        orgTerm.subAggregation(originalTargetGoodsNumber);
        orgTerm.subAggregation(platfromTargetGoodsNumber);
        orgTerm.subAggregation(originalOrderGoodsNumber);
        orgTerm.subAggregation(platfromOrderGoodsNumber);
        orgTerm.subAggregation(orderNumber);
        orgTerm.subAggregation(originalOrderAmount);
        orgTerm.subAggregation(platfromOrderAmount);
        orgTerm.subAggregation(originalReturnAmount);
        orgTerm.subAggregation(platfromReturnAmount);
        SearchResponse search = rest.search(INDEX, ElasticSearchRest.Page.of(1, 0), queryBuilder, null, Arrays.asList(orgTerm, count), null);

        Terms org = search.getAggregations().get("terms");
        List<SalesDataComparisonStatisticsVolumeView> result = org.getBuckets().stream().skip(query.getStartRow()).map(bucket -> {
            double inquiryGoodsNumberAgg = (((Sum) bucket.getAggregations().get("inquiryGoodsNumber")).getValue());
            double organizationIdAgg = ((Cardinality) bucket.getAggregations().get("organizationId")).getValue();
            double originalQuotationNumberAgg = ((Sum) bucket.getAggregations().get("originalQuotationNumber")).getValue();
            double platformQuotationNumberAgg = (((Sum) bucket.getAggregations().get("platformQuotationNumber")).getValue());
            double notQuotedGoodsNumberAgg = ((Sum) bucket.getAggregations().get("notQuotedGoodsNumber")).getValue();
            double originalTargetGoodsNumberAgg = ((Sum) bucket.getAggregations().get("originalTargetGoodsNumber")).getValue();
            double platfromTargetGoodsNumberAgg = ((Sum) bucket.getAggregations().get("platfromTargetGoodsNumber")).getValue();
            double originalOrderGoodsNumberAgg = ((Sum) bucket.getAggregations().get("originalOrderGoodsNumber")).getValue();
            double platfromOrderGoodsNumberAgg = (((Sum) bucket.getAggregations().get("platfromOrderGoodsNumber")).getValue());
            double orderNumberAgg = (((Sum) bucket.getAggregations().get("orderNumber")).getValue());
            double originalOrderAmountAgg = (((Sum) bucket.getAggregations().get("originalOrderAmount")).getValue());
            double platfromOrderAmountAgg = (((Sum) bucket.getAggregations().get("platfromOrderAmount")).getValue());
            double originalReturnAmountAgg = (((Sum) bucket.getAggregations().get("originalReturnAmount")).getValue());
            double platfromReturnAmountAgg = (((Sum) bucket.getAggregations().get("platfromReturnAmount")).getValue());
            String businessNameAgg = ((TopHits) bucket.getAggregations().get("businessName")).getHits().getHits()[0].getSourceAsMap().get("businessName").toString();

            return SalesDataComparisonStatisticsVolumeView.builder()
                    .businessName(businessNameAgg)
                    .customerActiveNumber(organizationIdAgg)
                    .inquiryGoodsNumber(inquiryGoodsNumberAgg)
                    .orderNumber(orderNumberAgg)
                    .originalQuotationNumber(originalQuotationNumberAgg)
                    .platformQuotationNumber(platformQuotationNumberAgg)
                    .platfromOrderGoodsNumber(notQuotedGoodsNumberAgg)
                    .originalTargetGoodsNumber(originalTargetGoodsNumberAgg)
                    .platfromTargetGoodsNumber(platfromTargetGoodsNumberAgg)
                    .originalOrderGoodsNumber(originalOrderGoodsNumberAgg)
                    .platfromOrderGoodsNumber(platfromOrderGoodsNumberAgg)
                    .originalOrderAmount(originalOrderAmountAgg)
                    .platfromOrderAmount(platfromOrderAmountAgg)
                    .originalReturnAmount(originalReturnAmountAgg)
                    .platfromReturnAmount(platfromReturnAmountAgg)
                    .build();
        }).collect(Collectors.toList());
        Aggregation countAgg = search.getAggregations().get("count");
        return RestResponse.success(((Cardinality) countAgg).getValue(), result);

    }

    /**
     * 查询构建
     *
     * @param query
     * @return
     */                     //获取查询生成器
    public BoolQueryBuilder getQueryBuilder(SalesDataComparisonStaticsQuery query) {
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        if (Objects.nonNull(query.getStart())) {
            boolQueryBuilder.must(QueryBuilders.rangeQuery("statisticsTime").gte(DateFormatUtils.format(query.getStart(), "yyyy-MM-dd")));
        }
        if (Objects.nonNull(query.getEnd())) {
            boolQueryBuilder.must(QueryBuilders.rangeQuery("statisticsTime").lt(DateFormatUtils.format(query.getEnd(), "yyyy-MM-dd")));
        }
        if (Objects.nonNull(query.getMemberName())) {
            boolQueryBuilder.must(QueryBuilders.matchQuery("customerName", query.getMemberName()));
        }
        return boolQueryBuilder;
    }
}
